package cn.ccew.sys.web.organization;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONSerializer;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.ccew.sys.model.SysOrgnization;
import cn.ccew.sys.web.SysBaseController;

@Controller
public class OrganizationController extends SysBaseController {
	/**
	 * 
	 * @param rootMenuCode
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("organization_load.wb")
	public void loadMenu(HttpServletResponse response, String pid) throws Exception {
		Criteria criteria = this.createCriteria(SysOrgnization.class);

		if (StringUtils.isEmpty(pid)) {
			criteria.add(Restrictions.isEmpty("org"));
		} else if (pid.equals("-1")) {
			criteria.add(Restrictions.isNull("org"));
		} else {
			criteria.add(Restrictions.eq("org.id", pid));
		}

		criteria.addOrder(Order.asc("priority"));
		// 关联查询时使用Distinct方法去除重复数据
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

		List<SysOrgnization> list = criteria.list();
		List<Map<Object, Object>> mapList = new ArrayList<Map<Object, Object>>();

		for (SysOrgnization temp : list) {
			mapList.add(getMapObj(temp));
		}

		writerTo(response, JSONSerializer.toJSON(mapList).toString());
	}

	/**
	 * 分页加载
	 * 
	 * @param rootMenuCode
	 * @param start
	 * @param limit
	 * @throws Exception
	 */
	@RequestMapping("organization_loadOrganizationList.wb")
	public void organization_loadOrganizationList(String pid, HttpServletRequest request, HttpServletResponse response) throws Exception {

		Criteria criteria = this.createCriteria(SysOrgnization.class);

		if (StringUtils.isEmpty(pid)) {
			criteria.add(Restrictions.isEmpty("org"));
		} else if (pid.equals("-1")) {
			criteria.add(Restrictions.isNull("org"));
			// criteria.add(Restrictions.and(Property.forName("org").ne(null),
			// criteria.setProjection(Projections.distinct(Property.forName("org"))).add(Restrictions.and(Property.forName("org").isNotEmpty(),
			// Property.forName("org").isNotNull()));
		} else {
			criteria.add(Restrictions.eq("org.id", pid));
		}

		criteria.addOrder(Order.asc("priority"));

		String[] excludes = new String[] { "chileren", "org", "createTime", "lastModifyTime" };

		responseListJSON(criteria, request, response, excludes);
	}

	/**
	 * 加载一条记录，用于显示修改
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("organization_loadOrganization.wb")
	public void organization_loadOrganization(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysOrgnization org = baseService.findById(id, SysOrgnization.class);
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("id", org.getId());
		map.put("rsName", org.getOrgName());
		map.put("priority", org.getPriority());

		String pid = "";
		if (null != org.getOrg()) {
			pid = org.getOrg().getId();
		}
		map.put("pid", pid);
		responseListJSON(response, map);
	}

	/**
	 * 修改一条记录 id存在为修改，否则创建
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("organization_saveOrganization.wb")
	public void organization_saveOrganization(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			SysOrgnization org = null;
			if (isParameterExist(request, "id")) {
				String id = request.getParameter("id");
				if (StringUtils.isNotEmpty(id)) {
					org = baseService.findById(id, SysOrgnization.class);
				}
			}
			if (null == org) {
				org = new SysOrgnization();
			}
			if (isParameterExist(request, "pid")) {
				SysOrgnization parent = baseService.findById(request.getParameter("pid"), SysOrgnization.class);
				org.setOrg(parent);
			}
			org.setOrgName(request.getParameter("orgName"));
			baseService.saveOrUpdate(org);
			writerSuccess(response, "保存成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			writerFailure(response, "保存失败");
			e.printStackTrace();
		}

	}

	/**
	 * 删除
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("organization_removeOrganization.wb")
	public void organization_removeOrganization(HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysOrgnization org = null;
		if (isParameterExist(request, "id")) {
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {
				org = baseService.findById(id, SysOrgnization.class);
			}
		}
		if (null == org) {
			writerFailure(response, "删除失败，没有找个记录");
			return;
		}
		if (org.getChileren().size() > 0) {
			writerFailure(response, "删除除失败，先删除下级目录");
			return;
		}
		try {
			baseService.delete(org.getId(), SysOrgnization.class);
			writerSuccess(response, "删除成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			writerFailure(response, "删除失败，未知原因");
		}

	}

	/**
	 * 把资源 对象封装成菜单对象
	 * 
	 * @param source
	 * @return
	 */
	private static Map<Object, Object> getMapObj(SysOrgnization org) {
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("id", org.getId());
		map.put("text", org.getOrgName());
		map.put("leaf", org.getLeaf());
		return map;
	}
}
